package org.kwisatz.proxybot.filters;

import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.kwisatz.proxybot.HttpQueryFilter;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

public class Translate extends HttpQueryFilter
{
	public Translate()
	{
		super("trans");
	}

	private static final Pattern PATTERN=Pattern.compile("^(\\S+) +(\\S+) +(.+)$");
	
	/** test */
	public static void main(String[] args)
	{
		try
		{
			PrintWriter pw=new PrintWriter(System.out);			
			new Translate().handleQuery("en fr you are the one", pw);
			pw.flush();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	protected void handleQuery(String arguments, PrintWriter out)
	{
		try
		{
			Matcher m = PATTERN.matcher(arguments);		
			if(m.matches())
			{
				String from=m.group(1);
				String to=m.group(2);
				String text=m.group(3);				
				String s=URLEncoder.encode(text, "UTF-8");
				PostMethod post = new PostMethod("http://translate.google.com/translate_t");
				s="text="+s+"&langpair="+from+"%7C"+to+"&hl=en&ie=UTF-8&oe=UTF-8";
				post.setRequestEntity(new StringRequestEntity(s));			
				httpClient.executeMethod(post);
				Document document=parseDOM(post.getResponseBodyAsStream(), "UTF-8");
				XPath xpath=XPathFactory.newInstance().newXPath();
				Node n = (Node) xpath.evaluate("//div[@id='result_box']",
					document, XPathConstants.NODE);
				out.println(getTextString(n));
				out.flush();
			}
			else
				clientNotice.println("Syntax: !trans <from> <to> <text>");
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
}

